//
//  HomeVC.m
//  SSC
//
//  Created by 红沙尘 on 17/6/8.
//  Copyright © 2017年 红沙尘. All rights reserved.
//

#import "HomeVC.h"
#import "SDCycleScrollView.h"
#import "BannerVC.h"
#import "GonggaoListVC.h"
#import "GonggaoDetailVC.h"
#import "TouzhujiluVC.h"
#import "TixianVC.h"
#import "ChongzhiVC.h"
#import "AppDelegate.h"

@interface HomeVC ()<SDCycleScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
{
    __weak IBOutlet UILabel *hhLabel;
    __weak IBOutlet UILabel *mmLabel;
    __weak IBOutlet UILabel *ssLabel;
    
    __weak IBOutlet UIScrollView *mainScrollView;
    
    __weak IBOutlet NSLayoutConstraint *lineA;
    
    __weak IBOutlet UILabel *qiLabel;
    __weak IBOutlet UILabel *nuchissueLabel;
    __weak IBOutlet UILabel *yikaiQiLabel;
    
    IBOutlet UIView *qixianView;
    IBOutlet UIView *touzhuView;
    IBOutlet UIView *gonggaoView;
    
    UIPageControl *pageControl;
    NSMutableArray *gonggaoArray;
    NSMutableArray *bannerArray;
    
    CGFloat bannerH;
    
//    NSTimeInterval seconds;
}



@property (nonatomic, copy) NSString *second;

@end

@implementation HomeVC


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self secondsRequest];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setTitle:@"赢龍娱乐"];
    self.navigationItem.leftBarButtonItem = CUSTOMVIEW([UIView new]);
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(secondsRequest) name:@"ApplicationWillEnterForeground" object:nil];
}

#pragma mark - IBAction

- (IBAction)chongzhi {
    [self.navigationController pushViewController:[[ChongzhiVC alloc] init] animated:YES];
}

- (IBAction)tixian {
    [self.navigationController pushViewController:[[TixianVC alloc] init] animated:YES];
}

- (IBAction)moreGonggao {
    [self.navigationController pushViewController:[[GonggaoListVC alloc] init] animated:YES];
}

- (IBAction)woyaotouzhu {
    self.tabBarController.selectedIndex = 1;
}

- (IBAction)touzhujilu {
    TouzhujiluVC *jilu = [[TouzhujiluVC alloc] init];
    [self.navigationController pushViewController:jilu animated:YES];
}

- (void)secondsRequest {

    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    if (app.otype == CaipiaoTypeUnknow) return;
    
    [SSCRequest queryCurrentIssueWithType:app.otype
                                  success:^(NSDictionary *responseObject) {
                                      
                                      NSDictionary *data = responseObject[@"data"];
                                      
                                      qiLabel.text = [NSString stringWithFormat:@"第%@期",data[@"issue"]];
                                      
                                      nuchissueLabel.text = data[@"moreissue"];
                                      yikaiQiLabel.text = [NSString stringWithFormat:@"%d",120 - [nuchissueLabel.text intValue]];
                                      
                                      [self app].seconds = [self secondsFromDate:data[@"endtime"] toDate:data[@"systime"]];
                                      
                                      [[NSNotificationCenter defaultCenter] postNotificationName:@"ResetQueryFutrueList" object:nil];
                                  } fail:^(NSError *error) {
                                      
                                  }];
}

- (void)updateSeconds {
    
    if ([self app].otype == CaipiaoTypeUnknow) return;
    
    if ([self app].seconds < 0) {
        [self secondsRequest];
        return;
    }
    
    int s = (int)[self app].seconds%60;
    int m = ((int)[self app].seconds/60)%60;
    int h = ((int)[self app].seconds/3600)%60;
    
    hhLabel.text = [NSString stringWithFormat:@"%.2d",h];
    mmLabel.text = [NSString stringWithFormat:@"%.2d",m];
    ssLabel.text = [NSString stringWithFormat:@"%.2d",s];
    
    [self app].seconds --;
    
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    [app.touzhuVC updateQi:qiLabel.text hh:hhLabel.text mm:mmLabel.text ss:ssLabel.text];
    [app.lanziVC  updateQi:qiLabel.text hh:hhLabel.text mm:mmLabel.text ss:ssLabel.text];
}

- (NSTimeInterval)secondsFromDate:(NSString *)fromDate toDate:(NSString *)toDate {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    
    NSDate *aDate = [formatter dateFromString:fromDate];
    NSDate *bDate = [formatter dateFromString:toDate];
    return [aDate timeIntervalSinceDate:bDate];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return MIN(gonggaoArray.count, 5);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GGCell"];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:@"GGCell"];
        cell.textLabel.font = [MTool fontOfSize:12];
        cell.textLabel.textColor = [UIColor colorWithHexString:@"#666666"];
    }
    
    NSDictionary *dict = gonggaoArray[indexPath.row];
    cell.textLabel.text = dict[@"title"];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    GonggaoDetailVC *vc = [[GonggaoDetailVC alloc] initWithDict:gonggaoArray[indexPath.row]];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - SDCycleScrollViewDelegate

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    BannerVC *vc = [[BannerVC alloc] initWithData:bannerArray[index]];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)cycleScrollViewDidScrollAtIndex:(NSInteger)index {
    
    pageControl.currentPage = index;
}

#pragma mark - private

- (void)setupData {

    [Userinfo standardUserinfo].timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                                         target:self
                                                                       selector:@selector(updateSeconds)
                                                                       userInfo:nil
                                                                        repeats:YES];
    
    //轮播图
    bannerArray = [[NSMutableArray alloc] init];

    [SSCRequest bannerListSuccess:^(NSDictionary *responseObject) {
        
        NSArray *data = responseObject[@"data"];
        
        NSMutableArray *array = @[].mutableCopy;
        
        for (int i = 0; i < data.count; i ++) {
            NSDictionary *dict = data[i];
            [array addObject:dict[@"picurl"]];
            [bannerArray addObject:dict];
        }
        
        if (array.count > 0) {
            [self addBannerWithURLArray:array];
        }
        
    } fail:^(NSError *error) {
        
    }];
    
    //公告
    gonggaoArray = [[NSMutableArray alloc] init];
    
    [SSCRequest queryNoticeListSuccess:^(NSDictionary *responseObject) {
        NSArray *data = responseObject[@"data"];
        [gonggaoArray addObjectsFromArray:data];
        [mainTableView reloadData];
    } fail:^(NSError *error) {
        
    }];
}

- (void)setupUI {
    
    [self labelLayer];
    
    CGFloat space = 12;
    
    bannerH = [MTool adapterHeight:200];
    
    mainTableView.rowHeight = mainTableView.height/5;
    mainTableView.estimatedRowHeight = mainTableView.height/5;

    //把开奖时间倒计时隐藏掉
    //qixianView.frame = CGRectMake(0, bannerH + space, ScreenWidth, 0);
    qixianView.frame = CGRectMake(0, bannerH + 0, ScreenWidth, 0);
    qixianView.clipsToBounds = YES;
//    [mainScrollView addSubview:qixianView];
    
    touzhuView.frame = CGRectMake(0, qixianView.bottom + space, ScreenWidth, 80);
    [mainScrollView addSubview:touzhuView];
    touzhuView.layer.borderColor = [UIColor colorWithHexString:@"#eeeeee"].CGColor;
    touzhuView.layer.borderWidth = LineHeight;
    
    for (int i = 1; i < 4; i ++) {
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake((ScreenWidth/4)*i, 0, LineHeight, touzhuView.height)];
        lineView.layer.borderColor = touzhuView.layer.borderColor;
        lineView.layer.borderWidth = touzhuView.layer.borderWidth;
        [touzhuView addSubview:lineView];
    }
    
    gonggaoView.frame = CGRectMake(0, touzhuView.bottom + space, ScreenWidth, 158);
    [mainScrollView addSubview:gonggaoView];
    
    CGFloat contentH = MAX(gonggaoView.bottom, ScreenHeight - 64- 49);
    
    mainScrollView.contentSize = CGSizeMake(ScreenWidth, contentH);
}

- (void)labelLayer {
    
    hhLabel.layer.cornerRadius  = 2;
    hhLabel.layer.masksToBounds = YES;
    mmLabel.layer.cornerRadius  = 2;
    mmLabel.layer.masksToBounds = YES;
    ssLabel.layer.cornerRadius  = 2;
    ssLabel.layer.masksToBounds = YES;
    
    lineA.constant = LineHeight;
}

- (void)addBannerWithURLArray:(NSMutableArray *)urlArray {
    
    CGRect cycleFrame = CGRectMake(0, 0, ScreenWidth, bannerH);

 //网络加载 --- 创建带标题的图片轮播器
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:cycleFrame
                                                                imageURLStringsGroup:urlArray];;
    cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
    cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    cycleScrollView.delegate = self;
    cycleScrollView.showPageControl = NO;
    cycleScrollView.dotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色

    pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, cycleScrollView.height - 20, ScreenWidth, 20)];
    pageControl.numberOfPages = urlArray.count;
    [cycleScrollView addSubview:pageControl];
    
    cycleScrollView.tag = 229230;
    [mainScrollView addSubview:cycleScrollView];
}

- (AppDelegate *)app {
    return (AppDelegate *)[UIApplication sharedApplication].delegate;;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
